// 打开统计弹窗
function openModal() {
    document.getElementById('statistics-modal').style.display = 'block';
    document.body.style.overflow = 'hidden'; // 防止背景滚动
}

// 关闭统计弹窗
function closeModal() {
    document.getElementById('statistics-modal').style.display = 'none';
    document.body.style.overflow = 'auto'; // 恢复背景滚动
}

// 点击弹窗外部关闭
window.onclick = function (event) {
    const modal = document.getElementById('statistics-modal');
    if (event.target === modal) {
        closeModal();
    }
}

// ESC键关闭弹窗
document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
        closeModal();
    }
});

// 切换时间范围选择
function toggleDateRange() {
    const timeRange = document.getElementById('time-range').value;
    const dateRangeDiv = document.getElementById('date-range');
    const latestRangeDiv = document.getElementById('latest-range');

    if (timeRange === 'range') {
        dateRangeDiv.classList.remove('hidden');
        dateRangeDiv.classList.add('show');
        latestRangeDiv.classList.add('hidden');
        latestRangeDiv.classList.remove('show');
    } else {
        dateRangeDiv.classList.add('hidden');
        dateRangeDiv.classList.remove('show');
        latestRangeDiv.classList.remove('hidden');
        latestRangeDiv.classList.add('show');
    }
}

// 单选按钮样式切换
document.addEventListener('DOMContentLoaded', function () {
    // 单选按钮事件监听
    document.querySelectorAll('input[name="stats-type"]').forEach(radio => {
        radio.addEventListener('change', function () {
            document.querySelectorAll('.radio-item').forEach(item => {
                item.classList.remove('checked');
            });
            this.closest('.radio-item').classList.add('checked');
        });
    });

    // 设置默认日期
    const today = new Date();
    const lastWeek = new Date();
    lastWeek.setDate(today.getDate() - 7);

    document.getElementById('end-date').value = today.toISOString().split('T')[0];
    document.getElementById('start-date').value = lastWeek.toISOString().split('T')[0];

    // 初始化界面状态
    toggleDateRange();
    
    // 为最近数据输入框添加验证监听
    document.getElementById('latest-value').addEventListener('input', function() {
        const value = parseInt(this.value);
        const unit = document.getElementById('latest-unit').value;
        const maxValue = unit === 'hours' ? 8760 : 365;
        
        if (value > maxValue) {
            this.value = maxValue;
        } else if (value < 1) {
            this.value = 1;
        }
    });
});

// 验证最近数据输入
function validateLatestInput() {
    const value = parseInt(document.getElementById('latest-value').value);
    const unit = document.getElementById('latest-unit').value;
    
    if (!value || value < 1) {
        alert('请输入有效的数量（大于0）');
        return false;
    }
    
    // 设置合理的最大值限制
    const maxValue = unit === 'hours' ? 8760 : 365; // 最多1年的小时数或天数
    if (value > maxValue) {
        alert(`${unit === 'hours' ? '小时' : '天'}数不能超过${maxValue}`);
        return false;
    }
    
    return true;
}

// 执行统计分析
function runStatistics(event) {
    const btn = event.target;
    const originalText = btn.textContent;

    btn.textContent = '分析中...';
    btn.classList.add('loading');
    btn.disabled = true;

    // 获取参数
    const statsType = document.querySelector('input[name="stats-type"]:checked').value;  // 'basic' 或 'defect_type'
    const timeRange = document.getElementById('time-range').value;  // 'latest' 或 'range'
    const startDate = document.getElementById('start-date').value;
    const endDate = document.getElementById('end-date').value;
    const resampleFreq = document.getElementById('resample-freq').value; // 重采样频率

    // 构造请求参数
    let time_range_spec = '';
    if (timeRange === 'latest') {
        // 验证最近数据输入
        if (!validateLatestInput()) {
            btn.textContent = originalText;
            btn.classList.remove('loading');
            btn.disabled = false;
            return;
        }
        
        const latestValue = parseInt(document.getElementById('latest-value').value);
        const latestUnit = document.getElementById('latest-unit').value;
        
        // 构造时间范围规格字符串
        time_range_spec = `latest_${latestUnit}:${latestValue}`;
    } else if (timeRange === 'range') {
        // 自定义范围
        if (startDate && endDate) {
            // 验证日期范围的合理性
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            if (start > end) {
                alert('开始日期不能晚于结束日期');
                btn.textContent = originalText;
                btn.classList.remove('loading');
                btn.disabled = false;
                return;
            }
            
            time_range_spec = {
                start: startDate,
                end: endDate
            };
        } else {
            alert('请设置起始和结束日期');
            btn.textContent = originalText;
            btn.classList.remove('loading');
            btn.disabled = false;
            return;
        }
    }

    // 构造请求体
    const requestBody = {
        time_range_spec: time_range_spec,
        type: statsType
    };

    // 只有在用户选择了重采样频率时才添加此参数
    if (resampleFreq) {
        requestBody.resample_freq = resampleFreq;
    }

    fetch('/api/statistics/detail', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
            return response.json();
        })
        .then(data => {
            // 显示结果
            document.getElementById('statistics-result').textContent = JSON.stringify(data, null, 2);
        })
        .catch(error => {
            document.getElementById('statistics-result').textContent = `❌ 统计数据获取失败: ${error.message}`;
        })
        .finally(() => {
            // 恢复按钮状态
            btn.textContent = originalText;
            btn.classList.remove('loading');
            btn.disabled = false;
        });
}
